package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.constants.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews>implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    //内容列表
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.条件封装执行查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
       //文章标题模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //频道id
        if (dto.getChannelId()!=null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //频道状态
        if (dto.getStatus()!=null){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //发布时间
        if (dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //当前自媒体文章
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId,user.getId());
        //按找创建时间倒序 （最新文章放在最前面）
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //3.执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //4.返回封装结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal(), pageResult.getRecords());
        result.setHost(webSite);
        return result;
    }
//发布文章
    @Override
    public ResponseResult saveNews(WmNewsDto dto, short isSubmit) {
        //1.检查参数
        if(dto==null||StringUtils.isBlank(dto.getContent())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或修改
        WmNews wmNews = new WmNews();
        //将dto里的参数值设置到wmNews 拷贝 属性
        BeanUtils.copyProperties(dto,wmNews);
        //暂时把type设置为null
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //处理文章 封面得前缀
        String  images=imageListToStr(dto.getImages(),webSite);
        wmNews.setImages(images);
        saveWmNews(wmNews,isSubmit);

        //3.关联文章和素材得关系
        List<Map> contents = JSON.parseArray(dto.getContent(), Map.class);
        List<String> materials = parseContentImages(contents);
        //3.1关联文章内容得图片和素材 关系
        //只有文章提交审核才保存文章和素材的关系
        if (isSubmit==WmNews.Status.SUBMIT.getCode()&&materials.size()>0){
            saveRelativeInfoForContent(materials,wmNews.getId());
        }
        if (isSubmit==WmNews.Status.SUBMIT.getCode()){
            saveRelativeInfoForCover(dto,materials,wmNews);
        }
        //TODO 4.发消息给admin审核文章

        //5.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

//查询文章详情
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        ResponseResult result=ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不在存在");
        }
        //判断文章状态 已上架并且已经发布则不能删除
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.WMNEWS_UP_ERROR);
        }
        //删除文章与素材关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在！");
        }
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前状态不是发布状态，不能上架或下架");

        }
        if (dto.getEnable()!=null&&dto.getEnable()>-1&&dto.getEnable()<2){
            update(Wrappers.<WmNews>lambdaUpdate()
            .eq(WmNews::getId,dto.getId())
                    .set(WmNews::getEnable,dto.getEnable()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询需要发布的文章id列表
     *
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        //查询状态为4或为8的数据且发布时间小于当前时间
        List<WmNews> list = list(Wrappers
                .<WmNews>lambdaQuery()
                .le(WmNews::getPublishTime, new Date())
                .in(WmNews::getStatus, 4, 8).select(WmNews::getId));
        List<Integer> idList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return idList;
    }


    //
//     关联文章  封面  中的图片和素材关系
//     @param dto  前端传递参数 # 得到 用户上传的 封面列表
//     @param materials  从文章内容中获取
//     @param wmNews 文章对象
//
    private void saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        // 1 得到用户上传的图片列表 images 带前缀
        // null 自动
        List<String> images = dto.getImages();

        // 用户选择自动
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            int size = materials.size();
            if ( size> 0 &&size <= 2) {  // 单图
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType( WemediaConstants.WM_NEWS_SINGLE_IMAGE );
            } else if (size > 2) {  // 多图
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType( WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else { // 无图
                wmNews.setType( WemediaConstants.WM_NEWS_NONE_IMAGE );
            }

            // 处理文章图片前缀
            if (images != null && images.size() > 0) {
                wmNews.setImages(imageListToStr(images, webSite));
            }

            // 更新文章数据
            updateById(wmNews);
        }

        // 保存文章封面图片 和 素材关系
        saveRelativeInfoForImage(images, wmNews.getId());
    }


//
//     保存文章图片和素材关系
//     @param materials  图片url列表
//     @param newsId
//    /
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }


//===================================================================================
//
//     执行保存 文章图片和素材关系
//     @param materials  图片url列表
//     @param newsId 文章id
//     @param type 类型 0：内容  1 封面
//
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {

        // 1 查询图片url对应的素材列表 4
        List<WmMaterial> dbWmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl,materials)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));

//        for (WmMaterial dbWmMaterial : dbWmMaterials) {
//            Map<String, Integer> map = new HashMap<>();
//            map.put(dbWmMaterial.getUrl(), dbWmMaterial.getId());
//        }
        // 数据库 Map  {"1.jpg":54, "2.jpg":55}
        List<Integer> materialIds = new ArrayList<>();

        Map<String, Integer> dbMap = dbWmMaterials.stream()
                .collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        for (String material : materials) {
            Integer id = dbMap.get(material);
            if (id == null) {
                throw new CustomException(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
            }
            materialIds.add(id);
        }

        //2 批量插入到数据库
        wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);

    }
    //===================================================================

    /**
     * 保存文章封面和素材关系
     * @param images  图片列表-带前缀
     * @param wmNewsId
     */
    private void saveRelativeInfoForImage(List<String> images, Integer wmNewsId) {
        // 把集合中的每一个图片前缀删除，并且处理空格，返回新的集合
        images = images.stream().map(image -> image
                .replace(webSite, "")
                .replace(" ", ""))
                .collect(Collectors.toList());

        saveRelativeInfo(images, wmNewsId, WemediaConstants.WM_IMAGE_REFERENCE);
    }

    /**
     * 保存文章图片和素材关系
     * @param materials  图片url列表
     * @param newsId
     */
    //=====================================================================
//
//     解析文章内内容中图片
//     @param contents  图片列表#不带图片前缀
//     @return
    private List<String> parseContentImages(List<Map> contents) {
        List<String> materials = new ArrayList<>();

        for (Map<String, String> material : contents) {
            if (material.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) {
                String imgUrl = material.get("value")
                        .replace(webSite,"")
                        .replace(" ","");
                materials.add(imgUrl);
            }
        }

        return materials;
    }


    private void saveWmNews(WmNews wmNews, Short isSubmit) {

        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UPENABLE); // 上架

        if (wmNews.getId() == null) { // 新增
            save(wmNews);
        } else {  // 修改
            //1 删除文章和素材关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

            //2 更新文章
            updateById(wmNews);
        }

    }


//============================================================================
//     处理前端传递文章封面图片列表 去除前缀，并且转换成字符串
//     material/2021/1/20210104/1.jpg,material/2021/1/20210101/2.jpg,material/2021/1/20210104/3.png
//
//     @param images
//     @param webSite
//     @return
//
    private String imageListToStr(List<String> images, String webSite) {

        return images.toString()
                .replace("[","")
                .replace("]","")
                .replace(webSite,"")
                .replace(" ","");
    }
}
